from flask import Flask, render_template, request
import query
from flask import Blueprint
from MySQL import mysql_c
from flask_cors import CORS

class_api = Blueprint('class_api', __name__)
CORS(class_api)	# 注册CORS

#新建一个班级
@class_api.route('/class_new', methods=['get', 'post'])
def newclass():
    if (request.method == 'POST'):
        cname = request.json.get('name') #班级名称
        tasknote = request.json.get('note') #班级备注
        teacherusernmae = request.json.get('teacherusernmae') #班级老师姓名
    else:
        cname = request.values.get('name')
        tasknote = request.values.get('note')
        teacherusernmae = request.values.get('teacherusernmae')

    if cname and teacherusernmae:
        if not tasknote:
            tasknote=""
        backinf = query.new_class(mysql_c, cname,tasknote,teacherusernmae)
        if backinf[0] == -1:
            return {"msg": "新增失败", "state": -1, "data": None}
        elif backinf[0] == 1:
            return {"msg": "新增成功", "state": 1, "data": backinf[1]}
    else:
        return {"msg": "数据不完整", "state": -1, "data": None}

#为班级插入一个学生
@class_api.route('/insert_student', methods=['get', 'post'])
def ins():
    if (request.method == 'POST'):
        username = request.json.get('username') #学生用户名
        classid = request.json.get('classid') #被插入的班级id
    else:
        username = request.values.get('username')
        classid = request.values.get('classid')

    if username and classid:
        backinf = query.insert_student_intoclass(mysql_c, username,classid)
        if backinf[0] == -1:
            return {"msg": "新增失败", "state": -1, "data": None}
        elif backinf[0] == 1:
            return {"msg": "新增成功", "state": 1, "data": backinf[1]}
    else:
        return {"msg": "数据不完整", "state": -1, "data": None}